<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/21 0021
 * Time: 下午 4:25
 */
namespace app\admin\controller;

use app\admin\model\Producttype;
use app\common\BaseHelper;
use app\common\model\Printer as PrinterModel;

use app\common\model\Printerconfig;
use app\common\validate\IDMustBePostiveInt;
use app\lib\exception\ParameterException;
use app\lib\feieyun\Prints;
use think\Db;
use think\Exception;
use think\Request;

class Printer extends Base
{
    public function index(){

        return $this->fetch();
    }

    public function indexApi(){
        $request = $this->request;
        $param = $request->param();

        $start = $param['start'];  // 每页起始条数
        $length = $param['length'];  // 每页显示条数
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];  //排序条件

        $where = [
            'businessId' => session('TENANT_ID')
        ];

        if(session('member')['roleType'] == 2) {
            $where['storeId'] = session('member')['storeId'];
        }

        $printer = new \app\common\model\Printer();
        $data = $printer->where($where)->limit($start, $length)->order($order)->select();
        foreach ($data as &$v){
            $store = \app\admin\model\Store::get($v['storeId']);
            $v->store = $store;
        }
        $count = $printer->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $data,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 添加或修改打印机
     * @param null $id
     * @return mixed|\think\response\Json
     */
    public function edit($id = null){

        /**
         * array(14) {
        ["id"] => string(0) ""
        ["name"] => string(3) "434"
        ["num"] => string(3) "434"
        ["keys"] => string(4) "4343"
        ["storeId"] => string(0) ""
        ["switch"] => array(4) {
        [0] => string(2) "on"
        [1] => string(2) "on"
        [2] => string(2) "on"
        [3] => string(2) "on"
        }
        ["printerNum1"] => string(1) "1"
        ["printerNum2"] => string(1) "1"
        ["printerMethod"] => string(1) "1"
        ["printerNum3"] => string(1) "1"
        ["duizhang"] => string(2) "on"
        ["chuping"] => string(2) "on"
        ["jiezhang"] => string(2) "on"
        ["isauto"] => string(2) "on"
        }
         */
        $newprinterconfig = [];
        if(empty($id)){
            $printer = new PrinterModel();
            $PrinterConfig = new Printerconfig();
        }else{
            $printer = \app\common\model\Printer::get($id);
            $printerconfig = Printerconfig::where(['printerId'=>$printer->id])->select()->toArray();
            foreach ($printerconfig as $k=>$v){
                if($v['sceneId']==1){
                    $newprinterconfig['duizhang'] = $v;
                }elseif ($v['sceneId']==2){
                    $newprinterconfig['chuping'] = $v;
                }else{
                    $newprinterconfig['jiezhang'] = $v;
                }
            }
        }

        if(request()->isPost()){
            $param = Request::instance()->param();
            $param['businessId'] = session('TENANT_ID');
            Db::startTrans();
            try{
                if(empty($id)){
                    //新增
                    $printers = $printer->where('businessId',session('TENANT_ID'))->select()->toArray();

                    if(BaseHelper::IsGetArray($param['code'],$printers)){
                        throw new ParameterException([
                            'msg' => '不能重复添加同一台打印机'
                        ]);
                    }

                    $printer->name = $param['name'];
                    $printer->businessId = $param['businessId'];
                    $printer->storeId = $param['storeId'];
                    $printer->code = $param['code'];
                    $printer->secretKey = $param['secretKey'];
                    $printer->type = $param['type'];
                    $printer->status = $param['status'];
                    $printer->peisong_status = $param['peisong_status'];
                    $printer->isauto = $param['isauto'];
                    if($printer->save()){

                        if(!$this->insertPrinterConfig($param,$printer->id)){
                            throw new ParameterException([
                                'msg' => '写入PrinterConfig失败'
                            ]);
                        }


                    }else{
                        throw new ParameterException([
                            'msg' => '写入Printer失败'
                        ]);
                    }

                    //添加打印机到飞鹅后台
                    //提示：打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填)，多台打印机请换行（\n）添加新打印机信息，每次最多100行(台)。
                    $str = $printer->code.'#'.$printer->secretKey.'#'.$printer->name.'#';
                    $result = Prints::addPrinter($str, $printer->type);
                    $result = json_decode($result);
                    if($result->msg != 'ok'){
                        throw new ParameterException([
                            'msg' => '打印机添失败'
                        ]);
                    }

                }else{
                    //修改

                    if($printer){
                        $printer->name = $param['name'];
                        $printer->storeId = $param['storeId'];
                        $printer->code = $param['code'];
                        $printer->secretKey = $param['secretKey'];
                        $printer->type = $param['type'];
                        $printer->status = $param['status'];
                        $printer->peisong_status = $param['peisong_status'];
                        $printer->isauto = $param['isauto'];
                        $printer->save();

                        $this->updatePrinterConfig($newprinterconfig,$param,$printer->id);

                    }else{
                        throw new ParameterException([
                            'msg' => '该打印机不存在'
                        ]);
                    }

                }
                Db::commit();
                return show(config('status.SUCCESS_STATUS'),'添加打印机成功','添加打印机成功');
            }catch (Exception $ex){
                Db::rollback();
                return show(config('status.ERROR_STATUS'),$ex->msg,$ex->msg);
            }


        }
        $store = \app\common\model\Store::where(['tenantId'=>session('TENANT_ID'),'isActive'=>1])->select();
        $cate = Producttype::where('tenantId',session('TENANT_ID'))->select();
        $this->assign('store',$store);
        $this->assign('cate',$cate);
        $this->assign('id',$id);
        $this->assign('printer',$printer);
        $this->assign('printerconfig',$newprinterconfig);
        return $this->fetch();
    }


    private function updatePrinterConfig($newprinterconfig,$param,$PrinterId){

        $PrinterConfigPost = $this->getPrinterConfigData($param,$PrinterId);
        $newPrinterConfigPost = [];
        foreach ($PrinterConfigPost as $v){
            if($v['sceneId']==1){
                $newPrinterConfigPost['duizhang'] = $v;
            }elseif ($v['sceneId']==2){
                $newPrinterConfigPost['chuping'] = $v;
            }else{
                $newPrinterConfigPost['jiezhang'] = $v;
            }
        }
        $update = [];
        if(isset($newPrinterConfigPost['duizhang'])){
            if(isset($newprinterconfig['duizhang'])){
                $data = [
                    'id' => $newprinterconfig['duizhang']['id'],
                    'number' => $newPrinterConfigPost['duizhang']['number'],
                    'status' => $newPrinterConfigPost['duizhang']['status']
                ];
                array_push($update,$data);
            }else{
                Printerconfig::create(
                    [
                        'printerId' => $newPrinterConfigPost['duizhang']['printerId'],
                        'sceneId'=> $newPrinterConfigPost['duizhang']['sceneId'],
                        'number' => $newPrinterConfigPost['duizhang']['number'],
                        'status' => $newPrinterConfigPost['duizhang']['status']
                    ]
                );
            }
        }else{
            if(isset($newprinterconfig['duizhang']) && $newprinterconfig['duizhang']['status']==10){
                $data = [
                    'id' => $newprinterconfig['duizhang']['id'],
                    'status'=>0,
                ];
                array_push($update,$data);
            }

        }
        if(isset($newPrinterConfigPost['chuping'])){
            if(isset($newprinterconfig['chuping'])){
                $data = [
                    'id' => $newprinterconfig['chuping']['id'],
                    'status' => $newPrinterConfigPost['chuping']['status'],
                    'number' => $newPrinterConfigPost['chuping']['number'],
                    'mode' => $newPrinterConfigPost['chuping']['mode'],
                    'type' => isset($newPrinterConfigPost['chuping']['type'])?$newPrinterConfigPost['chuping']['type']:NULL,
                ];
                array_push($update,$data);

            }else{
                Printerconfig::create(
                    [
                        'printerId' => $newPrinterConfigPost['chuping']['printerId'],
                        'sceneId' =>  $newPrinterConfigPost['chuping']['sceneId'],
                        'number' => $newPrinterConfigPost['chuping']['number'],
                        'mode' => $newPrinterConfigPost['chuping']['mode'],
                        'type' => isset($newPrinterConfigPost['chuping']['type'])?$newPrinterConfigPost['chuping']['type']:NULL,
                        'status' => $newPrinterConfigPost['chuping']['status']
                    ]
                );
            }
        }else{
            if(isset($newprinterconfig['chuping']) && $newprinterconfig['chuping']['status']==10){
                $data = [
                    'id' => $newprinterconfig['chuping']['id'],
                    'status' => 0,
                ];
                array_push($update,$data);
            }
        }
        if(isset($newPrinterConfigPost['jiezhang'])){
            if(isset($newprinterconfig['jiezhang'])){
                $data = [
                    'id' => $newprinterconfig['jiezhang']['id'],
                    'number' => $newPrinterConfigPost['jiezhang']['number'],
                    'status' => $newPrinterConfigPost['jiezhang']['status']
                ];
                array_push($update,$data);
            }else{
                Printerconfig::create(
                    [
                        'printerId' => $newPrinterConfigPost['jiezhang']['printerId'],
                        'sceneId' => $newPrinterConfigPost['jiezhang']['sceneId'],
                        'number' => $newPrinterConfigPost['jiezhang']['number'],
                        'status' => $newPrinterConfigPost['jiezhang']['status']
                    ]
                );
            }
        }else{
            if(isset($newprinterconfig['jiezhang']) && $newprinterconfig['jiezhang']['status'] == 10){
                $data = [
                    'id' => $newprinterconfig['jiezhang']['id'],
                    'status' => 0,
                ];
                array_push($update,$data);
            }
        }

        if($update){
            $p = new Printerconfig();
            $p->saveAll($update);
        }


    }


    private function insertPrinterConfig($param,$PrinterId){
        $flag = false;
        $PrinterConfig = $this->getPrinterConfigData($param,$PrinterId);
        $PrinterconfigModel = new Printerconfig();
        if($PrinterconfigModel->saveAll($PrinterConfig)){
            $flag = true;
        }
        return $flag;
    }

    private function getPrinterConfigData($param,$PrinterId){
        $PrinterConfig = [];
        global $i;
        $i = 0;
        if(isset($param['duizhang']) && $param['duizhang'] == 'on'){

            $PrinterConfig[$i]['sceneId'] = PrinterModel::sceneId_1;
            $PrinterConfig[$i]['printerId'] = $PrinterId;
            $PrinterConfig[$i]['status'] = 10;
            $PrinterConfig[$i]['number'] = isset($param['printerNum1'])?$param['printerNum1']:1;

            $i++;
        }
        if(isset($param['chuping']) && $param['chuping'] == 'on'){
            $PrinterConfig[$i]['sceneId'] = PrinterModel::sceneId_2;
            $PrinterConfig[$i]['printerId'] = $PrinterId;
            $PrinterConfig[$i]['status'] = 10;
            $PrinterConfig[$i]['number'] = isset($param['printerNum2'])?$param['printerNum2']:1;
            $param['printerMethod'] = isset($param['printerMethod'])?$param['printerMethod']:1;
            if($param['printerMethod'] == 1){
                $PrinterConfig[$i]['mode'] = '全部商品一单';
            }
            if($param['printerMethod'] == 2){
                $PrinterConfig[$i]['mode'] = '一个商品一单';
            }
            if($param['printerMethod'] == 3){
                $PrinterConfig[$i]['mode'] = '分类打印';
                //分类打印

                if(is_array($param['category'])){
                    $PrinterConfig[$i]['type'] = implode(',',$param['category']);
                }else{
                    $PrinterConfig[$i]['type'] = $param['category'];
                }

            }
            $i++;
        }
        if(isset($param['jiezhang']) && $param['jiezhang'] == 'on'){
            $PrinterConfig[$i]['sceneId'] = PrinterModel::sceneId_3;
            $PrinterConfig[$i]['printerId'] = $PrinterId;
            $PrinterConfig[$i]['status'] = 10;
            $PrinterConfig[$i]['number'] = isset($param['printerNum3'])?$param['printerNum3']:1;
        }
        return $PrinterConfig;

    }

    /**
     * 删除打印机
     * @return \think\response\Json
     */
    public function DelPrinter(){
        (new IDMustBePostiveInt())->goCheck();
        $status = 0;
        $message = '删除打印机失败';
        Db::startTrans();
        try{
            $id = input('post.id');
            $printer = \app\common\model\Printer::get($id);
            if(!$printer){
                throw new ParameterException([
                    'msg' => '该打印机不存在'
                ]);
            }
            if($printer->delete()){
                Printerconfig::where('printerId','=',$id)->delete();
                $code = $printer->code;
                $res = Prints::deletePrinter($code);
                $res = json_decode($res);
                if(isset($res->msg) && $res->msg == 'ok'){
                    $status = 1;
                    $message = '删除打印机成功';
                }

            }else{
                throw new ParameterException([
                    'msg' => '删除失败'
                ]);
            }
            Db::commit();
            return show($status,$message,$message);
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),$ex->msg,$ex->msg);
        }
    }
}